package com.liao.ticket.util;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class JwtUtils {
    private static final String jwtToken = "123456xiaoliao!@#$%^&";

    public static String createToken(Long id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", id);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken)   // 签发算法，秘钥为jwtToken
                .setClaims(claims) // body数据，要唯一，自行设置
                .setIssuedAt(new Date()) // 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + 12 * 60 * 60 * 1000));// 12小时的有效时间
        String token = jwtBuilder.compact();
        return token;
    }

    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            System.out.println("用户签证验证失败");
        }
        return null;
    }

    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        String token = JwtUtils.createToken(100L);
        String s;
        Scanner scanner = new Scanner(System.in);
        System.out.println("开始");
        while (true) {
            s = scanner.next();
            if(s.toLowerCase().equals("over")) break;
            if(s.equals("c")){
                System.out.println("token:"+token);
                System.out.println(JwtUtils.checkToken(token));
            }
        }
        System.out.println("结束");
    }
}
